import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../gen/assets.gen.dart';
import '../../common/styles/colors.dart';
import '../../entity/food_record.dart';

/// 生理周期数据模型
class MenstrualCycleData {
  final String month; // 月份，如 "10月"
  final List<MenstrualDayData> days; // 每天的数据

  MenstrualCycleData({
    required this.month,
    required this.days,
  });

  factory MenstrualCycleData.fromJson(Map<String, dynamic> json) {
    final resultVOS = json['resultVOS'] as List<dynamic>? ?? [];
    final days = resultVOS.map((item) => MenstrualDayData.fromJson(item as Map<String, dynamic>)).toList();
    
    return MenstrualCycleData(
      month: json['month'] as String? ?? '',
      days: days,
    );
  }
}

/// 生理周期单日数据
class MenstrualDayData {
  final String weekName; // 星期，如 "六"
  final String value; // 日期，如 "18"
  final String type; // 类型：0-无，1-生理期，2-排卵期

  MenstrualDayData({
    required this.weekName,
    required this.value,
    required this.type,
  });

  factory MenstrualDayData.fromJson(Map<String, dynamic> json) {
    return MenstrualDayData(
      weekName: json['weekName'] as String? ?? '',
      value: json['value'] as String? ?? '',
      type: json['type'] as String? ?? '0',
    );
  }

  /// 获取颜色
  Color getColor() {
    switch (type) {
      case '1':
        return const Color(0xFFFF5070); // 生理期 - 粉红色
      case '2':
        return const Color(0xFFFF931F); // 排卵期 - 橙色
      default:
        return const Color(0xFF2A2A2A); // 无 - 灰色
    }
  }
}

/// 状态页状态管理
class StatusState {
  /// 当前选中的底部导航栏索引
  RxInt currentIndex = 0.obs;

  /// 当前选中的日期
  Rx<DateTime> selectedDate = DateTime.now().obs;

  /// 是否正在加载
  RxBool isLoading = false.obs;

  /// 心情滑块值 (0.0 - 1.0)
  RxDouble moodValue = 0.1.obs;

  /// 当前情绪文本
  RxString currentMoodText = '非常不愉快'.obs;

  /// 当前情绪图标
  Rx<IconData> currentMoodIcon = Icons.sentiment_very_dissatisfied.obs;

  /// 当前情绪颜色（强制为 Rx<Color> 避免 MaterialColor 泛型不匹配）
  Rx<Color> currentMoodColor = Rx<Color>(Colors.red);

  /// 情绪分段条当前选择下标（0~4），-1 表示未选择
  RxInt selectedMoodIndex = (-1).obs;

  /// 是否已经记录过情绪
  RxBool hasMoodRecorded = false.obs;

  /// 状态文本
  RxString statusText = '状态页面'.obs;

  /// 当前数据
  RxString currentData = '暂无数据'.obs;

  /// 错误信息
  RxString errorMessage = ''.obs;

  /// 是否有错误
  bool get hasError => errorMessage.value.isNotEmpty;

  /// 获取图标颜色
  Color getIconColor(bool isActive) {
    final isDark = Get.isDarkMode;
    if (isActive) {
      return const Color(0xffED5C2F);
    }
    return isDark
        ? Colours.dark_unselected_item_color
        : Colours.unselected_item_color;
  }

  /// 获取当前激活的索引
  int get activeIndex => currentIndex.value;

  /// 底部导航栏项目
  List<BottomNavigationBarItem> get bottomNavItems => [
        _buildNavItem(0, Assets.tabbar.statusActive, '状态'),
        _buildNavItem(1, Assets.tabbar.sleep, '睡眠'),
        _buildNavItem(2, Assets.tabbar.insight, '洞察'),
        _buildNavItem(3, Assets.tabbar.action, '行动'),
        _buildNavItem(4, Assets.tabbar.user, '我的'),
      ];

  /// 构建导航栏项目
  BottomNavigationBarItem _buildNavItem(
      int index, AssetGenImage asset, String label) {
    final isDark = Get.isDarkMode;
    final backgroundColor = isDark
        ? const Color.fromRGBO(40, 37, 40, 0.35)
        : const Color.fromRGBO(245, 245, 245, 0.35);
    final inactiveColor = isDark
        ? Colours.dark_unselected_item_color
        : Colours.unselected_item_color;

    return BottomNavigationBarItem(
      backgroundColor: backgroundColor,
      icon: asset.image(
        width: 26,
        height: 26,
        color: inactiveColor,
      ),
      activeIcon: asset.image(
        width: 26,
        height: 26,
        color: const Color(0xffED5C2F),
      ),
      label: label,
    );
  }

  /// 获取所有可用的图表资源
  List<AssetGenImage> get availableAssets => [
        Assets.tabbar.statusActive,
        Assets.tabbar.sleep,
        Assets.tabbar.insight,
        Assets.tabbar.action,
        Assets.tabbar.user,
      ];

  /// 根据索引获取对应的图表资源
  AssetGenImage getAssetByIndex(int index) {
    if (index >= 0 && index < availableAssets.length) {
      return availableAssets[index];
    }
    return Assets.tabbar.statusActive; // 默认返回状态图标
  }

  /// 获取当前激活的图表资源
  AssetGenImage get currentAsset => getAssetByIndex(activeIndex);

  /// 最近一次饮食记录数据（用于 UI 展示）
  Rxn<FoodRecord> latestFoodRecord = Rxn<FoodRecord>();

  /// 饮食记录列表（最多显示5条）
  RxList<FoodRecord> foodRecordList = <FoodRecord>[].obs;

  /// 是否展开显示所有饮食记录（超过3条时使用）
  RxBool isExpanded = false.obs;

  /// 是否展开健康计划区域（控制从"生命关键指标看板"到"今日事件小计"的折叠）
  RxBool isHealthPlanExpanded = true.obs;

  /// 每日营养目标值（可以根据用户设置调整）
  final double dailyCaloriesTarget = 1865.0;
  final double dailyCarbTarget = 98.0;
  final double dailyProteinTarget = 56.0;
  final double dailyFatTarget = 67.0;

  /// 当日已摄入营养素总量（可以从多条记录累加）
  RxDouble totalCalories = 0.0.obs;
  RxDouble totalCarbohydrate = 0.0.obs;
  RxDouble totalProtein = 0.0.obs;
  RxDouble totalFat = 0.0.obs;

  /// 计算剩余可摄入卡路里
  double get remainingCalories => (dailyCaloriesTarget - totalCalories.value)
      .clamp(0.0, dailyCaloriesTarget);

  /// 计算卡路里进度（0.0 - 1.0）
  double get caloriesProgress =>
      (totalCalories.value / dailyCaloriesTarget).clamp(0.0, 1.0);

  /// 更新营养数据（当有新的饮食记录时调用）
  void updateNutritionData(FoodRecord record) {
    latestFoodRecord.value = record;

    // 添加到列表开头（最新的在前面）
    foodRecordList.insert(0, record);

    // 保持列表最多5条记录
    if (foodRecordList.length > 5) {
      foodRecordList.removeRange(5, foodRecordList.length);
    }

    // 重新计算总营养素
    _recalculateNutrition();
  }

  /// 设置饮食记录列表（从服务器加载时调用）
  void setFoodRecordList(List<FoodRecord> records) {
    print('📝 StatusState: 设置饮食记录列表，接收到 ${records.length} 条记录');
    foodRecordList.value = records.take(5).toList(); // 最多取5条
    print('📝 StatusState: 实际设置了 ${foodRecordList.length} 条记录');

    if (records.isNotEmpty) {
      latestFoodRecord.value = records.first;
      print('📝 StatusState: 设置最新记录: ${records.first.foodName}');
    }

    // 重新计算总营养素
    _recalculateNutrition();
    print('📝 StatusState: 营养计算完成 - 卡路里: ${totalCalories.value}');
  }

  /// 重新计算营养素总量
  void _recalculateNutrition() {
    totalCalories.value = 0.0;
    totalCarbohydrate.value = 0.0;
    totalProtein.value = 0.0;
    totalFat.value = 0.0;

    for (final record in foodRecordList) {
      if (record.calories != null) {
        totalCalories.value += record.calories!;
      }
      if (record.carbohydrate != null) {
        totalCarbohydrate.value += record.carbohydrate!;
      }
      if (record.protein != null) {
        totalProtein.value += record.protein!;
      }
      if (record.fat != null) {
        totalFat.value += record.fat!;
      }
    }
  }

  /// 重置当日营养数据（新的一天开始时调用）
  void resetDailyNutrition() {
    totalCalories.value = 0.0;
    totalCarbohydrate.value = 0.0;
    totalProtein.value = 0.0;
    totalFat.value = 0.0;
    foodRecordList.clear();
    latestFoodRecord.value = null;
  }

  /// 活动数据（从API获取）
  Rxn<ActivityData> activityData = Rxn<ActivityData>();

  /// 更新活动数据
  void updateActivityData(ActivityData data) {
    activityData.value = data;
    print('🏃 StatusState: 更新活动数据 - 步数: ${data.steps}, 卡路里: ${data.calories}, 运动时间: ${data.sportTime}');
  }

  /// 获取步数进度（0.0 - 1.0）
  double get stepsProgress {
    final data = activityData.value;
    if (data == null || data.goalsSteps == 0) return 0.0;
    return (data.steps / data.goalsSteps).clamp(0.0, 1.0);
  }

  /// 获取卡路里进度（0.0 - 1.0）
  double get caloriesProgressForActivity {
    final data = activityData.value;
    if (data == null || data.goalsCalories == 0) return 0.0;
    return (data.calories / data.goalsCalories).clamp(0.0, 1.0);
  }

  /// 获取运动时间进度（0.0 - 1.0）
  double get sportTimeProgress {
    final data = activityData.value;
    if (data == null || data.goalsSportTime == 0) return 0.0;
    return (data.sportTime / data.goalsSportTime).clamp(0.0, 1.0);
  }

  /// 今日压力列表数据（用于压力图表显示和上传，保留null值）
  RxList<int?> todayStressList = <int?>[].obs;

  /// 当前压力值
  RxInt currentStress = 0.obs;

  /// 情绪状态数据
  RxString emotionalStateValue = ''.obs; // 情绪状态值 (1-5)
  RxString emotionalRecordDate = ''.obs; // 记录日期
  RxString emotionalWeekName = ''.obs; // 星期
  RxString emotionalRecordTime = ''.obs; // 记录时间
  
  /// 情绪状态记录列表（包含多个时间点的情绪记录）
  RxList<EmotionalStateRecord> emotionalStateList = <EmotionalStateRecord>[].obs;

  /// 上次情绪记录时间（用于1小时冷却检查）
  Rx<DateTime?> lastEmotionalRecordTime = Rx<DateTime?>(null);

  /// 状态评分数据（按日期存储）
  RxMap<String, int> statusScoreMap = <String, int>{}.obs;

  /// 更新今日压力列表数据
  void updateTodayStressList(List<int?> stressList) {
    print('📊 StatusState: 更新压力列表数据，数据点数量: ${stressList.length}');
    todayStressList.value = stressList;
    print('📊 StatusState: 压力列表已更新，当前列表长度: ${todayStressList.length}');
    // 注意：不再从列表中更新 currentStress，因为应该使用 API 返回的 average 值
    // currentStress 的值由 _loadEmotionalInfoData 方法中的 average 字段设置
  }

  /// 更新情绪状态数据
  void updateEmotionalStateData({
    required String emotionalState,
    required String recordDate,
    required String weekName,
    required String recordTime,
    List<EmotionalStateRecord>? emotionalRecords,
  }) {
    print('😊 StatusState: 开始更新情绪状态数据');
    print('😊 StatusState: emotionalState=$emotionalState, recordDate=$recordDate, recordTime=$recordTime');
    print('😊 StatusState: emotionalRecords数量=${emotionalRecords?.length ?? 0}');
    
    emotionalStateValue.value = emotionalState;
    emotionalRecordDate.value = recordDate;
    emotionalWeekName.value = weekName;
    emotionalRecordTime.value = recordTime;
    
    // 始终更新情绪状态记录列表（包括空列表）
    emotionalStateList.value = emotionalRecords ?? [];
    print('😊 StatusState: 设置情绪记录列表，数量: ${emotionalStateList.length}');
    
    for (var record in emotionalStateList) {
      print('😊 StatusState: 记录详情 - 状态: ${record.emotionalState}, 时间: ${record.recordTime}');
    }
    
    // 更新最后记录时间（使用列表中最新的记录时间，即第一条记录）
    if (emotionalRecords != null && emotionalRecords.isNotEmpty) {
      try {
        final latestRecord = emotionalRecords.first; // 列表第一条是最新的
        final parsedTime = _parseRecordTime(latestRecord.recordTime);
        if (parsedTime != null) {
          lastEmotionalRecordTime.value = parsedTime;
          print('😊 StatusState: 更新最后记录时间: ${lastEmotionalRecordTime.value}');
        }
      } catch (e) {
        print('❌ StatusState: 解析记录时间失败: $e');
      }
    } else {
      // 如果没有记录，清空最后记录时间
      print('😊 StatusState: 没有情绪记录，清空最后记录时间');
    }
    
    // 将情绪状态映射到UI的选中索引 (1-5 -> 0-4)
    final stateIndex = int.tryParse(emotionalState) ?? 0;
    print('😊 StatusState: 解析情绪状态 - emotionalState: $emotionalState, stateIndex: $stateIndex');
    print('😊 StatusState: 当前UI状态 - selectedMoodIndex: ${selectedMoodIndex.value}, hasMoodRecorded: ${hasMoodRecorded.value}');
    
    if (stateIndex >= 1 && stateIndex <= 5) {
      // 检查是否可以记录新情绪（1小时冷却）
      if (canRecordMood()) {
        // 冷却时间已过，重置为未记录状态
        hasMoodRecorded.value = false;
        selectedMoodIndex.value = -1;
        print('😊 StatusState: 冷却时间已过，重置为未记录状态');
      } else {
        // 冷却时间内，显示已记录状态
        selectedMoodIndex.value = stateIndex - 1;
        _updateMoodStateByIndex(stateIndex - 1);
        hasMoodRecorded.value = true;
        print('😊 StatusState: 冷却时间内，显示已记录状态 - selectedMoodIndex: ${selectedMoodIndex.value}');
      }
    } else {
      // 如果没有情绪状态，重置UI状态
      hasMoodRecorded.value = false;
      selectedMoodIndex.value = -1;
      print('😊 StatusState: API返回的情绪状态无效或为空，重置UI状态');
    }
    
    print('😊 StatusState: 更新情绪状态数据完成 - 状态: $emotionalState, 日期: $recordDate, 时间: $recordTime, 记录数: ${emotionalRecords?.length ?? 0}');
  }

  /// 解析记录时间字符串为 DateTime（用于比较）
  DateTime? _parseRecordTime(String timeStr) {
    try {
      final timeParts = timeStr.split(':');
      if (timeParts.length == 2) {
        final hour = int.parse(timeParts[0]);
        final minute = int.parse(timeParts[1]);
        final now = DateTime.now();
        return DateTime(now.year, now.month, now.day, hour, minute);
      }
    } catch (e) {
      print('❌ StatusState: 解析时间失败: $timeStr, 错误: $e');
    }
    return null;
  }

  /// 根据分段索引更新情绪状态
  void _updateMoodStateByIndex(int index) {
    String moodText;
    Color moodColor;
    switch (index) {
      case 0:
        moodText = '非常不愉快';
        moodColor = const Color(0xFF3662FF);
        break;
      case 1:
        moodText = '有点不愉快';
        moodColor = const Color(0xFF2FA7A0);
        break;
      case 2:
        moodText = '无悲无喜';
        moodColor = const Color(0xFF3AB37A);
        break;
      case 3:
        moodText = '有点愉快';
        moodColor = const Color(0xFFCC8E3A);
        break;
      default:
        moodText = '非常愉快';
        moodColor = const Color(0xFFB0466B);
        break;
    }
    currentMoodText.value = moodText;
    currentMoodColor.value = moodColor;
  }

  /// 检查是否可以记录新的情绪（1小时冷却）
  bool canRecordMood() {
    final lastTime = lastEmotionalRecordTime.value;
    if (lastTime == null) {
      print('😊 canRecordMood: lastTime为null，可以记录');
      return true; // 从未记录过，可以记录
    }
    
    final now = DateTime.now();
    final difference = now.difference(lastTime);
    final canRecord = difference.inHours >= 1;
    
    print('😊 canRecordMood: lastTime=$lastTime, now=$now, difference=${difference.inMinutes}分钟, canRecord=$canRecord');
    
    // 检查是否已经过了1小时
    return canRecord;
  }

  /// 获取距离下次可记录的剩余时间（分钟）
  int getRemainingCooldownMinutes() {
    final lastTime = lastEmotionalRecordTime.value;
    if (lastTime == null) {
      return 0;
    }
    
    final now = DateTime.now();
    final difference = now.difference(lastTime);
    final remainingMinutes = 60 - difference.inMinutes;
    
    return remainingMinutes > 0 ? remainingMinutes : 0;
  }

  /// 获取压力状态描述
  String get stressStatus {
    final stress = currentStress.value;
    if (stress <= 30) return '放松';
    if (stress <= 60) return '适中';
    if (stress <= 80) return '较高';
    return '高压';
  }

  /// 获取压力状态颜色
  Color get stressColor {
    final stress = currentStress.value;
    if (stress <= 30) return Colors.green;
    if (stress <= 60) return Colors.orange;
    if (stress <= 80) return Colors.red;
    return Colors.red.shade700;
  }

  /// 今日事件小计列表
  RxList<DailyEventSummary> dailyEventsList = <DailyEventSummary>[].obs;

  /// 是否正在加载事件小计
  RxBool isLoadingDailyEvents = false.obs;

  /// 更新今日事件小计数据
  void updateDailyEventsList(List<DailyEventSummary> events) {
    dailyEventsList.value = events;
    print('📝 StatusState: 更新今日事件小计数据 - 事件数量: ${events.length}');
  }

  /// 模块布局配置列表
  RxList<ModuleLayoutConfig> moduleLayoutList = <ModuleLayoutConfig>[].obs;

  /// 是否正在加载布局配置
  RxBool isLoadingLayout = false.obs;

  /// 更新模块布局配置
  void updateModuleLayout(List<ModuleLayoutConfig> layouts) {
    moduleLayoutList.value = layouts;
    print('📐 StatusState: 更新模块布局配置 - 模块数量: ${layouts.length}');
  }

  /// 获取显示的模块列表（按sort排序）
  /// 如果API返回空数据，则显示所有默认模块
  List<ModuleLayoutConfig> get displayedModules {
    // 如果布局列表为空，返回默认的所有模块
    if (moduleLayoutList.isEmpty) {
      return _getDefaultModules();
    }
    
    // 否则按照API返回的配置显示
    return moduleLayoutList
        .where((module) => module.moduleDisplay == '0')
        .toList()
      ..sort((a, b) => a.sort.compareTo(b.sort));
  }
  
  /// 获取默认模块列表（当API返回空时使用）
  List<ModuleLayoutConfig> _getDefaultModules() {
    return [
      ModuleLayoutConfig(
        moduleName: '身体状况图',
        moduleDisplay: '0',
        moduleSign: '0',
        sort: 1,
      ),
      ModuleLayoutConfig(
        moduleName: '健康计划',
        moduleDisplay: '0',
        moduleSign: '1',
        sort: 2,
      ),
      ModuleLayoutConfig(
        moduleName: '生命关键指标看板',
        moduleDisplay: '0',
        moduleSign: '2',
        sort: 3,
      ),
      ModuleLayoutConfig(
        moduleName: '饮食记录',
        moduleDisplay: '0',
        moduleSign: '3',
        sort: 4,
      ),
      ModuleLayoutConfig(
        moduleName: '情绪管理',
        moduleDisplay: '0',
        moduleSign: '4',
        sort: 5,
      ),
      ModuleLayoutConfig(
        moduleName: '压力',
        moduleDisplay: '0',
        moduleSign: '5',
        sort: 6,
      ),
      ModuleLayoutConfig(
        moduleName: '今日事件小计',
        moduleDisplay: '0',
        moduleSign: '6',
        sort: 7,
      ),
      ModuleLayoutConfig(
        moduleName: '心率',
        moduleDisplay: '0',
        moduleSign: '7',
        sort: 8,
      ),
      ModuleLayoutConfig(
        moduleName: '心率变异性',
        moduleDisplay: '0',
        moduleSign: '8',
        sort: 9,
      ),
      ModuleLayoutConfig(
        moduleName: '睡眠',
        moduleDisplay: '0',
        moduleSign: '9',
        sort: 10,
      ),
      ModuleLayoutConfig(
        moduleName: '血氧饱和度',
        moduleDisplay: '0',
        moduleSign: '10',
        sort: 11,
      ),
      ModuleLayoutConfig(
        moduleName: '活动',
        moduleDisplay: '0',
        moduleSign: '11',
        sort: 12,
      ),
      ModuleLayoutConfig(
        moduleName: '锻炼记录',
        moduleDisplay: '0',
        moduleSign: '12',
        sort: 13,
      ),
      ModuleLayoutConfig(
        moduleName: '生理周期',
        moduleDisplay: '0',
        moduleSign: '13',
        sort: 14,
      ),
    ];
  }

  /// 卡片数据 - 心率信息
  RxInt averageHeartRate = 0.obs;
  RxList<HeartRatePoint> heartRateList = <HeartRatePoint>[].obs;
  RxString heartRateStartTime = ''.obs; // 睡眠开始时间
  RxString heartRateEndTime = ''.obs; // 睡眠结束时间

  /// 卡片数据 - HRV信息
  RxInt averageHrv = 0.obs;
  RxList<HrvPoint> hrvList = <HrvPoint>[].obs;

  /// 卡片数据 - 睡眠信息
  Rxn<SleepCardData> sleepCardData = Rxn<SleepCardData>();

  /// 卡片数据 - 睡眠血氧信息
  Rxn<SleepBloodOxygenData> sleepBloodOxygenData = Rxn<SleepBloodOxygenData>();

  /// 卡片数据 - 血氧信息
  RxInt averageBloodOxygen = 0.obs;
  RxList<BloodOxygenPoint> bloodOxygenList = <BloodOxygenPoint>[].obs;

  /// 卡片数据 - 运动记录信息
  Rxn<ExerciseRecordData> exerciseRecordData = Rxn<ExerciseRecordData>();

  /// 更新心率卡片数据
  void updateHeartRateCardData(int average, List<HeartRatePoint> list, {String? startTime, String? endTime}) {
    averageHeartRate.value = average;
    heartRateList.value = list;
    if (startTime != null) heartRateStartTime.value = startTime;
    if (endTime != null) heartRateEndTime.value = endTime;
    print('💓 StatusState: 更新心率卡片数据 - 平均心率: $average, 数据点: ${list.length}, 睡眠时间: $startTime - $endTime');
  }

  /// 更新HRV卡片数据
  void updateHrvCardData(int average, List<HrvPoint> list) {
    averageHrv.value = average;
    hrvList.value = list;
    print('🫀 StatusState: 更新HRV卡片数据 - 平均HRV: $average, 数据点: ${list.length}');
  }

  /// 更新睡眠卡片数据
  void updateSleepCardData(SleepCardData data) {
    sleepCardData.value = data;
    print('😴 StatusState: 更新睡眠卡片数据 - 睡眠时长: ${data.sleepDuration}');
  }

  /// 更新睡眠血氧卡片数据
  void updateSleepBloodOxygenData(SleepBloodOxygenData data) {
    sleepBloodOxygenData.value = data;
    print('🩸 StatusState: 更新睡眠血氧卡片数据');
  }

  /// 更新血氧卡片数据
  void updateBloodOxygenCardData(int average, List<BloodOxygenPoint> list) {
    averageBloodOxygen.value = average;
    bloodOxygenList.value = list;
    print('🩸 StatusState: 更新血氧卡片数据 - 平均血氧: $average, 数据点: ${list.length}');
  }

  /// 更新运动记录卡片数据
  void updateExerciseRecordData(ExerciseRecordData data) {
    exerciseRecordData.value = data;
    print('🏃 StatusState: 更新运动记录卡片数据');
  }

  /// 生理周期数据
  Rx<MenstrualCycleData?> menstrualCycleData = Rx<MenstrualCycleData?>(null);

  /// 更新生理周期数据
  void updateMenstrualCycleData(MenstrualCycleData data) {
    menstrualCycleData.value = data;
    print('🩸 StatusState: 更新生理周期数据 - 月份: ${data.month}, 天数: ${data.days.length}');
  }

  /// 看板数据
  Rxn<DashboardData> dashboardData = Rxn<DashboardData>();

  /// 更新看板数据
  void updateDashboardData(DashboardData data) {
    dashboardData.value = data;
    print('📊 StatusState: 更新看板数据');
  }

  /// 身体状况评分数据
  Rxn<ConditionScoreData> conditionScoreData = Rxn<ConditionScoreData>();

  /// 更新身体状况评分数据
  void updateConditionScoreData(ConditionScoreData data) {
    conditionScoreData.value = data;
    print('💯 StatusState: 更新身体状况评分数据 - 总分: ${data.totalScore}');
  }

  /// 用餐类型列表
  RxList<MealTypeOption> mealTypeList = <MealTypeOption>[].obs;

  /// 是否正在加载用餐类型
  RxBool isLoadingMealTypes = false.obs;

  /// 更新用餐类型列表
  void updateMealTypeList(List<MealTypeOption> types) {
    mealTypeList.value = types;
    print('🍽️ StatusState: 更新用餐类型列表 - 类型数量: ${types.length}');
  }
}

/// 用餐类型选项模型
class MealTypeOption {
  final String label;
  final String value;

  MealTypeOption({
    required this.label,
    required this.value,
  });

  factory MealTypeOption.fromJson(Map<String, dynamic> json) {
    return MealTypeOption(
      label: json['dictLabel']?.toString() ?? '',
      value: json['dictValue']?.toString() ?? '',
    );
  }
}

/// 看板数据模型
class DashboardData {
  final int steps;
  final int sleepScore;
  final int heartRate;
  final int heartHrv;
  final int bloodOxygen;
  final String timing;
  final String compareHeartRate;
  final String compareHeartHrv;
  final int planStepCount;
  final String planSleepQuality;
  final String planRestingHeartRate;
  final String planHeartRateVariability;
  final String planBloodOxygenSaturation;
  final String abnormalValue;
  final List<String> abnormalValues;

  DashboardData({
    required this.steps,
    required this.sleepScore,
    required this.heartRate,
    required this.heartHrv,
    required this.bloodOxygen,
    required this.timing,
    required this.compareHeartRate,
    required this.compareHeartHrv,
    required this.planStepCount,
    required this.planSleepQuality,
    required this.planRestingHeartRate,
    required this.planHeartRateVariability,
    required this.planBloodOxygenSaturation,
    required this.abnormalValue,
    required this.abnormalValues,
  });

  factory DashboardData.fromJson(Map<String, dynamic> json) {
    // 解析 abnormalValues 列表
    List<String> abnormalValuesList = [];
    if (json['abnormalValues'] != null && json['abnormalValues'] is List) {
      for (var item in json['abnormalValues']) {
        if (item != null) {
          abnormalValuesList.add(item.toString());
        }
      }
    }

    return DashboardData(
      steps: json['steps'] ?? 0,
      sleepScore: json['sleepScore'] ?? 0,
      heartRate: json['heartRate'] ?? 0,
      heartHrv: json['heartHrv'] ?? 0,
      bloodOxygen: json['bloodOxygen'] ?? 0,
      timing: json['timing']?.toString() ?? '',
      compareHeartRate: json['compareHeartRate']?.toString() ?? '',
      compareHeartHrv: json['compareHeartHrv']?.toString() ?? '',
      planStepCount: json['planStepCount'] ?? 0,
      planSleepQuality: json['planSleepQuality']?.toString() ?? '',
      planRestingHeartRate: json['planRestingHeartRate']?.toString() ?? '',
      planHeartRateVariability: json['planHeartRateVariability']?.toString() ?? '',
      planBloodOxygenSaturation: json['planBloodOxygenSaturation']?.toString() ?? '',
      abnormalValue: json['abnormalValue']?.toString() ?? '',
      abnormalValues: abnormalValuesList,
    );
  }
}

/// 身体状况评分数据模型
class ConditionScoreData {
  final int sleepDurationScore;
  final int deepSleepRatioScore;
  final int sleepEfficiencyScore;
  final int napScore;
  final int sleepTotalScore;
  final int bmiScore;
  final int stepsScore;
  final int distanceScore;
  final int caloriesScore;
  final int sportTotalScore;
  final int eventTotalScore;
  final List<EventScoreVO> eventScoreVOList;
  final int emotionScore;
  final int pressureScore;
  final int emotionalStressScore;
  final int breakfastScore;
  final int lunchScore;
  final int dinnerScore;
  final int otherScore;
  final int foodTotalScore;
  final int rateScore;
  final int hrvScore;
  final int oxygenScore;
  final int physicalSignsScore;
  final int totalScore;

  ConditionScoreData({
    required this.sleepDurationScore,
    required this.deepSleepRatioScore,
    required this.sleepEfficiencyScore,
    required this.napScore,
    required this.sleepTotalScore,
    required this.bmiScore,
    required this.stepsScore,
    required this.distanceScore,
    required this.caloriesScore,
    required this.sportTotalScore,
    required this.eventTotalScore,
    required this.eventScoreVOList,
    required this.emotionScore,
    required this.pressureScore,
    required this.emotionalStressScore,
    required this.breakfastScore,
    required this.lunchScore,
    required this.dinnerScore,
    required this.otherScore,
    required this.foodTotalScore,
    required this.rateScore,
    required this.hrvScore,
    required this.oxygenScore,
    required this.physicalSignsScore,
    required this.totalScore,
  });

  factory ConditionScoreData.fromJson(Map<String, dynamic> json) {
    // 解析事件评分列表
    List<EventScoreVO> eventList = [];
    if (json['eventScoreVOList'] != null && json['eventScoreVOList'] is List) {
      for (var item in json['eventScoreVOList']) {
        if (item != null && item is Map<String, dynamic>) {
          eventList.add(EventScoreVO.fromJson(item));
        }
      }
    }

    return ConditionScoreData(
      sleepDurationScore: json['sleepDurationScore'] ?? 0,
      deepSleepRatioScore: json['deepSleepRatioScore'] ?? 0,
      sleepEfficiencyScore: json['sleepEfficiencyScore'] ?? 0,
      napScore: json['napScore'] ?? 0,
      sleepTotalScore: json['sleepTotalScore'] ?? 0,
      bmiScore: json['bmiScore'] ?? 0,
      stepsScore: json['stepsScore'] ?? 0,
      distanceScore: json['distanceScore'] ?? 0,
      caloriesScore: json['caloriesScore'] ?? 0,
      sportTotalScore: json['sportTotalScore'] ?? 0,
      eventTotalScore: json['eventTotalScore'] ?? 0,
      eventScoreVOList: eventList,
      emotionScore: json['emotionScore'] ?? 0,
      pressureScore: json['pressureScore'] ?? 0,
      emotionalStressScore: json['emotionalStressScore'] ?? 0,
      breakfastScore: json['breakfastScore'] ?? 0,
      lunchScore: json['lunchScore'] ?? 0,
      dinnerScore: json['dinnerScore'] ?? 0,
      otherScore: json['otherScore'] ?? 0,
      foodTotalScore: json['foodTotalScore'] ?? 0,
      rateScore: json['rateScore'] ?? 0,
      hrvScore: json['hrvScore'] ?? 0,
      oxygenScore: json['oxygenScore'] ?? 0,
      physicalSignsScore: json['physicalSignsScore'] ?? 0,
      totalScore: json['totalScore'] ?? 0,
    );
  }
}

/// 事件评分VO模型
class EventScoreVO {
  final String? eventInfo;
  final String? recordScores;

  EventScoreVO({
    this.eventInfo,
    this.recordScores,
  });

  factory EventScoreVO.fromJson(Map<String, dynamic> json) {
    return EventScoreVO(
      eventInfo: json['eventInfo']?.toString(),
      recordScores: json['recordScores']?.toString(),
    );
  }

  /// 判断是否有事件信息
  bool get hasEventInfo => eventInfo != null && eventInfo!.isNotEmpty;
}

/// 心率数据点
class HeartRatePoint {
  final String timeLabel;
  final int value;

  HeartRatePoint({
    required this.timeLabel,
    required this.value,
  });

  factory HeartRatePoint.fromJson(Map<String, dynamic> json) {
    return HeartRatePoint(
      timeLabel: json['timeLabel']?.toString() ?? '',
      value: int.tryParse(json['value']?.toString() ?? '0') ?? 0,
    );
  }
}

/// HRV数据点
class HrvPoint {
  final String timeLabel;
  final int value;

  HrvPoint({
    required this.timeLabel,
    required this.value,
  });

  factory HrvPoint.fromJson(Map<String, dynamic> json) {
    return HrvPoint(
      timeLabel: json['timeLabel']?.toString() ?? '',
      value: int.tryParse(json['value']?.toString() ?? '0') ?? 0,
    );
  }
}

/// 血氧数据点
class BloodOxygenPoint {
  final String timeLabel;
  final int value;

  BloodOxygenPoint({
    required this.timeLabel,
    required this.value,
  });

  factory BloodOxygenPoint.fromJson(Map<String, dynamic> json) {
    return BloodOxygenPoint(
      timeLabel: json['key']?.toString() ?? '',
      value: int.tryParse(json['value']?.toString() ?? '0') ?? 0,
    );
  }
}

/// 睡眠卡片数据
class SleepCardData {
  final String sleepDuration;
  final String longSleepDuration;
  final String? shortSleepDuration;
  final String? shortSleepStartTime;
  final String? shortSleepEndTime;
  final String startDate;
  final String endDate;
  final int sleepDurationMinute;
  final Map<String, dynamic>? maps;

  SleepCardData({
    required this.sleepDuration,
    required this.longSleepDuration,
    this.shortSleepDuration,
    this.shortSleepStartTime,
    this.shortSleepEndTime,
    required this.startDate,
    required this.endDate,
    required this.sleepDurationMinute,
    this.maps,
  });

  factory SleepCardData.fromJson(Map<String, dynamic> json) {
    return SleepCardData(
      sleepDuration: json['sleepDuration']?.toString() ?? '--',
      longSleepDuration: json['longSleepDuration']?.toString() ?? '--',
      shortSleepDuration: json['shortSleepDuration']?.toString(),
      shortSleepStartTime: json['shortSleepStartTime']?.toString(),
      shortSleepEndTime: json['shortSleepEndTime']?.toString(),
      startDate: json['startDate']?.toString() ?? '--',
      endDate: json['endDate']?.toString() ?? '--',
      sleepDurationMinute: json['sleepDurationMinute'] ?? 0,
      maps: json['maps'] as Map<String, dynamic>?,
    );
  }
}

/// 睡眠血氧数据
class SleepBloodOxygenData {
  final int? average;
  final int? restHeartRate;
  final String? startDate;
  final String? endDate;
  final List<dynamic>? heartRateList;

  SleepBloodOxygenData({
    this.average,
    this.restHeartRate,
    this.startDate,
    this.endDate,
    this.heartRateList,
  });

  factory SleepBloodOxygenData.fromJson(Map<String, dynamic> json) {
    return SleepBloodOxygenData(
      average: json['average'],
      restHeartRate: json['restHeartRate'],
      startDate: json['startDate']?.toString(),
      endDate: json['endDate']?.toString(),
      heartRateList: json['heartRateList'] as List<dynamic>?,
    );
  }
}

/// 运动记录数据
class ExerciseRecordData {
  final int? exerciseTime;
  final int? exerciseCalorie;
  final int? total;

  ExerciseRecordData({
    this.exerciseTime,
    this.exerciseCalorie,
    this.total,
  });

  factory ExerciseRecordData.fromJson(Map<String, dynamic> json) {
    return ExerciseRecordData(
      exerciseTime: json['exerciseTime'],
      exerciseCalorie: json['exerciseCalorie'],
      total: json['total'],
    );
  }
}

/// 模块布局配置模型
class ModuleLayoutConfig {
  final String moduleName;
  final String moduleDisplay; // '0'显示, '1'隐藏
  final String moduleSign;
  final int sort;

  ModuleLayoutConfig({
    required this.moduleName,
    required this.moduleDisplay,
    required this.moduleSign,
    required this.sort,
  });

  factory ModuleLayoutConfig.fromJson(Map<String, dynamic> json) {
    return ModuleLayoutConfig(
      moduleName: json['moduleName']?.toString() ?? '',
      moduleDisplay: json['moduleDisplay']?.toString() ?? '0',
      moduleSign: json['moduleSign']?.toString() ?? '0',
      sort: int.tryParse(json['sort']?.toString() ?? '0') ?? 0,
    );
  }
}

/// 今日事件小计模型
class DailyEventSummary {
  final String eventText;
  final String score;
  final String aiComment;
  final bool isPositive;

  DailyEventSummary({
    required this.eventText,
    required this.score,
    required this.aiComment,
    required this.isPositive,
  });

  factory DailyEventSummary.fromJson(Map<String, dynamic> json) {
    final scoreValue = json['recordScores']?.toString() ?? '0';
    final scoreNum =
        int.tryParse(scoreValue.replaceAll(RegExp(r'[+-]'), '')) ?? 0;
    final isPositive = scoreValue.startsWith('+') ||
        (!scoreValue.startsWith('-') && scoreNum > 0);

    return DailyEventSummary(
      eventText: json['eventInfo']?.toString() ?? '',
      score: scoreValue.startsWith('+') || scoreValue.startsWith('-')
          ? '$scoreValue分'
          : '$scoreValue分',
      aiComment: '小A管家：${json['aiCcomments']?.toString() ?? ''}',
      isPositive: isPositive,
    );
  }
}

/// 活动数据模型
class ActivityData {
  final double goalsCalories;
  final double goalsSteps;
  final double goalsSportTime;
  final double calories;
  final double steps;
  final double sportTime;
  final int caloriesScore;
  final int stepsScore;
  final int sportTimeScore;

  ActivityData({
    required this.goalsCalories,
    required this.goalsSteps,
    required this.goalsSportTime,
    required this.calories,
    required this.steps,
    required this.sportTime,
    required this.caloriesScore,
    required this.stepsScore,
    required this.sportTimeScore,
  });

  factory ActivityData.fromJson(Map<String, dynamic> json) {
    return ActivityData(
      goalsCalories: (json['goalsCalories'] ?? 0.0).toDouble(),
      goalsSteps: (json['goalsSteps'] ?? 0.0).toDouble(),
      goalsSportTime: (json['goalsSportTime'] ?? 0.0).toDouble(),
      calories: (json['calories'] ?? 0.0).toDouble(),
      steps: (json['steps'] ?? 0.0).toDouble(),
      sportTime: (json['sportTime'] ?? 0.0).toDouble(),
      caloriesScore: json['caloriesScore'] ?? 0,
      stepsScore: json['stepsScore'] ?? 0,
      sportTimeScore: json['sportTimeScore'] ?? 0,
    );
  }
}

/// 情绪状态记录模型
class EmotionalStateRecord {
  final String emotionalState; // 情绪状态值 (1-5)
  final String recordTime; // 记录时间 (HH:mm)

  EmotionalStateRecord({
    required this.emotionalState,
    required this.recordTime,
  });

  factory EmotionalStateRecord.fromJson(Map<String, dynamic> json) {
    return EmotionalStateRecord(
      emotionalState: json['emotionalState']?.toString() ?? '',
      recordTime: json['recordTime']?.toString() ?? '',
    );
  }

  /// 获取情绪对应的图片资源路径
  String get moodImagePath {
    switch (emotionalState) {
      case '1':
        return 'assets/images/status/very_unhappy.png';
      case '2':
        return 'assets/images/status/little_unhappy.png';
      case '3':
        return 'assets/images/status/none_feeling.png';
      case '4':
        return 'assets/images/status/little_happy.png';
      case '5':
        return 'assets/images/status/very_happy.png';
      default:
        return 'assets/images/status/none_feeling.png';
    }
  }
}
